package com.aipartner.security;

import com.aipartner.util.JwtUtil;
import com.aipartner.util.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT Authentication Filter
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private final JwtUtil jwtUtil;
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    private static final String[] PUBLIC_PATHS = new String[]{
            "/api/user/wechat/login",
            "/api/user/login/wechat",
            "/api/user/wechat-login",
            "/api/actuator/**",
            "/actuator/**",
            "/v2/api-docs",
            "/swagger-resources/**",
            "/swagger-ui/**",
            "/doc.html",
            "/health",
            "/api/ai-image/examples",
            "/api/ai-image/examples/*/detail",
            "/illustrate-images/**",
            "/uploads/**",
            "/images/**",
            "/icons/**",
            "/uploads/user-examples/**",
            "/uploads/generated-images/**",
            "/uploads/reference-images/**"
    };
    
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, 
                                   @NonNull FilterChain filterChain) throws ServletException, IOException {
        
        try {
            // 跳过公开路径的鉴权
            String uri = request.getRequestURI();
            for (String p : PUBLIC_PATHS) {
                if (PATH_MATCHER.match(p, uri)) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
            String jwt = getJwtFromRequest(request);
            
            if (StringUtils.hasText(jwt) && jwtUtil.validateToken(jwt)) {
                Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(jwt));
                String username = jwtUtil.getUsernameFromToken(jwt);
                
                // Set user context for current request
                UserContext.setCurrentUser(userId, username);
                
                // Create authentication token
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception ex) {
            log.error("Could not set user authentication in security context", ex);
        }
        
        try {
            filterChain.doFilter(request, response);
        } finally {
            // Clear user context after request
            UserContext.clear();
        }
    }
    
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}